//
//  GPXParser.m
//  Henry
//
//  Created by Ron Olson on 3/10/10.
//  Copyright 2010 Keep Bertha Surfin. All rights reserved.
//

#import "GPXParser.h"
#import "Waypoint.h"

@implementation GPXParser

/* We really want a filename, so the general init will not do */
-(id)init
{
	[self dealloc];
	@throw [NSException exceptionWithName:@"WrongInitcall" reason:@"This class is useless without a filename" userInfo:nil];
	return nil;
}

-(id)initWithGPXFilename:(NSString*)theFilename
{
	if (![super init])
		return nil;
	
	gpxFileName = theFilename;
	
	return self;
}

-(NSArray*)processFile
{
	NSMutableArray *wptsArray = [[NSMutableArray alloc] init];
	
	NSError *xmlError;
	NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:gpxFileName] options:NSXMLDocumentTidyXML error:&xmlError];
	NSLog(@"Size is %d", [[xmlDoc XMLData] length]);
	
	NSXMLElement* root  = [xmlDoc rootElement];
	
	NSArray* objectElements = [root nodesForXPath:@"//wpt" error:&xmlError];
	for(NSXMLElement* xmlElement in objectElements)
	{
		/* Here's the name (GC****) */
		NSString *cacheName;
		NSArray *nameElements = [xmlElement nodesForXPath:@"name" error:nil];
		for(NSXMLElement *nameElement in nameElements)
		{
			cacheName = [nameElement stringValue];
		}
		
		/* And the description */
		NSString *cacheDescription;
		NSArray *descElements = [xmlElement nodesForXPath:@"desc" error:nil];
		for(NSXMLElement *descElement in descElements)
		{
			cacheDescription = [descElement stringValue];
		}
		
		/* Create our new waypoint object */
		Waypoint *wpt = [[Waypoint alloc] initWithName:cacheName description:cacheDescription latitude:[[[xmlElement attributeForName:@"lat"] stringValue] doubleValue] longitude:[[[xmlElement attributeForName:@"lon"] stringValue] doubleValue]];
		
		[wptsArray addObject:wpt];
	}
	
	[xmlDoc release];
	
	return wptsArray;
}

@end
